'''
复星联合康乐一生重大疾病保险C款（升级版）
'''
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode
from threading import Thread

class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "复星联合康乐一生重大疾病保险C款（升级版）"
    # 生成产品数据
    def genProductInfo(self):
        plan = {

            "planA":{
                # 年龄段
                "year":[str(i) for i in range(0,5)],
                #性别
                "gender":["M","F"],
                #保障期限
                "expire":["70岁","80岁","终身"],
                #缴费期限
                "interval":["5","10","15","20","30"],
                #保额
                "money":[str(i) + "0000" for i in range(5,35,5)],
                # 投保人豁免
                "ext_item":["N"]

            },
            "planB":{

                # 年龄段
                "year": [str(i) for i in range(5, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期限
                "interval": ["5", "10", "15", "20", "30"],
                # 保额
                "money": [str(i) + "0000" for i in range(5, 55, 5)],
                # 投保人豁免
                "ext_item": ["N"]

            },
            "planC":{
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期限
                "interval": ["5", "10", "15", "20", "30"],
                # 保额
                "money": [str(i) + "0000" for i in range(5, 35, 5)],
                # 投保人豁免
                "ext_item": ["N"]

            }
        }
        num = 0
        for k in plan:
            for v in product( plan[k]["year"],plan[k]["gender"],plan[k]["expire"],plan[k]["interval"],plan[k]["money"],plan[k]["ext_item"]):
                num+=1
                #写入数据库
                self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                    v[0],v[1],v[2],v[3],v[4],v[5]
                ))
                self.mysql._conn.commit()
                print(

                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], v[4], v[5]
                    )

                )

    #执行爬虫
    def requestJson(self,dt=None,mysql=None):

        data = {

            "BTsc0060000000020151_TextAge": ""+dt["year"]+"Y",
            "BTsc0060000000020152_Sex": dt["gender"],
            "BTsc0060000000020153_Period": "0L" if dt["expire"] == "终身" else dt["expire"].replace("岁","A"),
            "BTsc0060000000020154_FeeYear": dt["interval"] + "Y",
            "BTsc0060000000020155_Plan": dt["money"],
            "BTsc0060000000020160_Occup": "1 - 6",
            "BTsc0060000000020161_AppTextAge": "29Y",
            "BTsc0060000000020162_AppSex": "M",
            "duty": "226101006001 - {0}, 226101006002 - 0, 226101006003 - 0, 226101006004 - 0".format( dt["money"]),
            "productid": "226101006",
            "complicatedFlag": "Y",
            "channelSn": "agent_pc",
            "userTrack":"",
            "pointExchangeFlag":"N"
        }
        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "成功！" in r.text :

            price = Helper.decimalParse( r.json()["data"]["productInitPrice"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("/*产品更新价格失败:%d*/"%dt["id"])

    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        for i in range(3):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()
